#pragma once
#include"../comm/log.hpp"
#include<iostream>
#include<string>
#include<assert.h>
#include<vector>
#include<fstream>
#include<cstdlib>
#include"../comm/util.hpp"
#include<unordered_map>
#include"include/mysql.h"
//根据list,加载所有题目信息
//用于数据交互，对外提供访问接口
namespace ns_model
{
    using namespace ns_log;
    using namespace std;
    using namespace ns_util;
    //题目内容详情
    struct Question
    {
        std::string number;
        std::string title;
        std::string star;
        std::string desc;
        std::string header;
        std::string tail;
        int cpu_limt;
        int mem_limt;
    };
    //给出题目列表路径，便于获取所有题目基本信息
    //const std::string question_list="./questions/questions.list";
    //给出主路径，便于查找单一目的题目信息
    //std::string path="./questions/";
    const std::string oj_questions="oj_questions";
    const std::string host="127.0.0.1";
    const std::string user="oj_client";
    const std::string passwd="123456";
    const std::string db="oj";
    const int port=3306;

    class Model
    {
    public:
    

    Model()
    {}
    ~Model()
    {}
    bool QueryMysql(const std::string &sql,vector<Question>*out)
    {
        //创建句柄
        MYSQL *my=mysql_init(nullptr);
        //链接数据库
        if(mysql_real_connect(my,host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0)==nullptr)
        {
            LOG(FATAL)<<"链接数据库失败"<<"\n";
            return false;
        }
        //设置编码格式,否则网页会乱码
        mysql_set_character_set(my,"utf8");
        LOG(INFO)<<"连接数据库成功";

        //执行sql语句
        if(mysql_query(my,sql.c_str())!=0)
        {
            LOG(WARNING)<<sql<<"execue error"<<"\n";
            return false;
        }

        //提取结果
        MYSQL_RES*res=mysql_store_result(my);

        //分析结果
        int rows=mysql_num_rows(res);
        int cols=mysql_num_fields(res);

        Question q;
        for(int i=0;i<rows;i++)
        {
            MYSQL_ROW row=mysql_fetch_row(res);
            q.number=row[0];
            q.title=row[1];
            q.star=row[2];
            q.desc=row[3];
            q.header=row[4];
            q.tail=row[5];
            q.cpu_limt=atoi(row[6]);
            q.mem_limt=atoi(row[7]);

            out->push_back(q);
        }

        //释放空间
        free(res);
        //关闭数据库链接 
        mysql_close(my);

        return true;
    }

    bool GetAllQuestions(vector<Question>*out)
    {
        std::string sql="select * from";
        sql+=oj_questions;
        return QueryMysql(sql,out);
    }
    bool GetOneQuestions(const std::string &number,Question*q)
    {
        bool res=false;
        std::string sql="select * from";
        sql+=oj_questions;
        sql+=" where number=";
        sql+=number;
        vector<Question>resault;
        
        if(QueryMysql(sql,&resault))
        {
            if(resault.size()==1)
            {
                (*q)=resault[0];
                res=true;
            }
        }
        return res;
    }
    private:
        
    };
}